//
//  BindVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/11/12.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "BindVC.h"
#import "MyCollectionVC.h"
@interface BindVC ()
@property (weak, nonatomic) IBOutlet UIButton *getMsgBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumTF;
@property (weak, nonatomic) IBOutlet UITextField *getCodeTF;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,assign) int indexURL;
@property (weak, nonatomic) IBOutlet UIButton *clickBindBtn;
@property(nonatomic,strong) NSString *randomNumber;
@property(nonatomic,strong) NSString *headImg;
@property(nonatomic,strong) NSString *nickName;
//@property(nonatomic,strong) NSString *qqOpenID;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@property (weak, nonatomic) IBOutlet UIButton *logInBtn;
@property(nonatomic,strong) MyCollectionVC *myCollectionVC;
@end

@implementation BindVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.manager = [AFHTTPSessionManager manager];
    self.nickName = [UserDefaultsHelper readNickName];
    self.headImg = [UserDefaultsHelper readHeadimg];
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
    flow.minimumLineSpacing = 0;
    flow.minimumInteritemSpacing = 0;
    self.myCollectionVC = [[MyCollectionVC alloc]initWithCollectionViewLayout:flow];
    XLog(@"[UserDefaultsHelper readHeadimg]:%@",[UserDefaultsHelper readHeadimg]);
    XLog(@"[UserDefaultsHelper readNickName]:%@",[UserDefaultsHelper readNickName]);
    self.getMsgBtn.userInteractionEnabled = NO;
    [self.getMsgBtn setTitleColor:kLabel102Color forState:UIControlStateNormal];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusuccess:) name:@"qingqiusuccess" object:nil];
    self.logInBtn.layer.masksToBounds = YES;
    self.logInBtn.layer.cornerRadius = 6;
    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请绑定手机号"];
}
-(void)qingqiusuccess:(NSNotification *)info
{
    NSString *message = [info.userInfo objectForKey:@"message"];
    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [WSProgressHUD dismiss];
        [self.navigationController popViewControllerAnimated:YES];
    });
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (IBAction)phoneNumTF:(UITextField *)sender {
    if (sender.text.length >= 11) {
        
        [sender resignFirstResponder];
        sender.text = [sender.text substringToIndex:11];
        self.getMsgBtn.userInteractionEnabled = YES;
        [self.getMsgBtn setTitleColor:kOrangeBg forState:UIControlStateNormal];
        //        //XLog(@"shoujiTF:%@----textField:%@",self.shoujiTF.text,textField.text);
    }else if (sender.text.length < 11) {
        self.getMsgBtn.userInteractionEnabled = NO;
        [self.getMsgBtn setTitleColor:kLabel102Color forState:UIControlStateNormal];
    }
}
- (IBAction)getCodeTF:(UITextField *)sender {
}
#pragma mark-代理:获取验证码
- (IBAction)getMegBtn:(UIButton *)sender {
    ///user/smsSend
    //#define kUrl @"http://192.168.0.131:8081/sj"
    self.indexURL = 9;
    XLog(@"self.phoneNumTF.text:%@",self.phoneNumTF.text);
    //    self.dict  = nil;
    if (self.phoneNumTF.text.length <11) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入手机号码"];
    }else if (![PhoneAndMailCheckObject phoneNumberIsTrue:self.phoneNumTF.text]) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"手机号码不正确,请重新输入"];
    }else{
        [self openCountdown];
        self.dict = @{
                      @"phone": self.phoneNumTF.text,
                      };
        XLog(@"dict:%@",self.dict);
        self.urlString = [NSString stringWithFormat:@"%@/user/smsSend",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *message = [responseObject objectForKey:@"message"];
            NSInteger integer = [[responseObject objectForKey:@"status"] intValue];
            if (integer == 200) {
            }else {
                
            }
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [WSProgressHUD dismiss];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
//        [CustomeManager POSTWithURLIndex:self.indexURL parameters:self.dict success:^(NSDictionary *dict) {
//
//        } failure:^(NSError *error) {
//
//        }];
        
    }
}
#pragma mark-绑定手机号码
- (IBAction)clickBind:(UIButton *)sender {
    
    if (self.phoneNumTF.text.length<11) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入手机号码"];
    }else if (![PhoneAndMailCheckObject phoneNumberIsTrue:self.phoneNumTF.text]) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"手机号码不正确,请重新输入"];
    }else if (self.getCodeTF.text.length <4) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入验证码"];
    }else {
        self.indexURL = 4;
        self.dict = @{
                      @"openid":self.openid,
                      @"phone": self.phoneNumTF.text,
                      @"code": self.getCodeTF.text
                      };
        XLog(@"绑定手机号码self.dict:%@",self.dict);
        self.urlString = [NSString stringWithFormat:@"%@/user/loginByQQBind",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            NSString *message = [responseObject objectForKey:@"message"];
            NSInteger integer = [[responseObject objectForKey:@"status"] intValue];
            if (integer == 200) {
                NSDictionary *date = [responseObject objectForKey:@"date"];
                NSDictionary *user = [date objectForKey:@"user"];
                NSString *headImg = [user objectForKey:@"headimg"];
                NSString *uid = [user objectForKey:@"id"];
                NSString *phone = [user objectForKey:@"phone"];
                NSString *type = [user objectForKey:@"type"];
                NSString *nickname = [user objectForKey:@"nickname"];
                NSString *token = [date objectForKey:@"token"];
                NSString *isAgreement = [date objectForKey:@"isAgreement"];
                /**
                 {
                 "date": {
                 "user": {
                 "id": 12,
                 "headimg": "427e576f1f50.png",
                 "phone": "17621764088",
                 "password": null,
                 "createtime": null,
                 "type": 1,
                 "nickname": "啦啦啦"
                 },
                 "token": "V-t2caKCf9sCk6GXYz7uB90PrSgH2WRL"
                 },
                 "message": "登录成功",
                 "status": 200
                 }
                 */
                if (nickname.length != 0 &&headImg.length != 0) {
                    [UserDefaultsHelper savePhoneHeadImg:@"" withHeadImgValue:headImg saveUid:@"" withUidValue:uid saveNickname:@"" withNicknameValue:self.nickName savePhone:@"" withPhone:phone saveType:@"" andType:type saveToken:@"" withTokenValue:token saveIsAgreement:@"" withIsAgreementValue:isAgreement];
                }else if (nickname.length == 0 &&headImg.length != 0) {
                    [UserDefaultsHelper savePhoneNONickNameHeadImg:@"" withHeadImgValue:headImg saveUid:@"" withUidValue:uid savePhone:@"" withPhone:phone saveType:@"" andType:type saveToken:@"" withTokenValue:token saveIsAgreement:@"" withIsAgreementValue:isAgreement];
                }else if (nickname.length != 0 &&headImg.length == 0) {
                    [UserDefaultsHelper savePhoneNOHeadImgUid:@"" withUidValue:uid saveNickname:@"" withNicknameValue:nickname savePhone:@"" withPhone:phone saveType:@"" andType:type saveToken:@"" withTokenValue:token saveIsAgreement:@"" withIsAgreementValue:isAgreement];
                    
                }else {
                    [UserDefaultsHelper saveType:@"" value:type];
                    [UserDefaultsHelper saveIphone:@"" value:phone];
                    [UserDefaultsHelper saveToken:@"" value:token];
                    [UserDefaultsHelper saveUid:@"" value:uid];
                }
                [UserDefaultsHelper saveAutoLogIn:@"" value:@"YES"];
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
                [self dismissViewControllerAnimated:YES completion:nil];
                 [self.myCollectionVC reloadInternet];
//                MyCollectionVC *vc = [[MyCollectionVC alloc]init];
//                [vc reloadInternet];
                self.headImg = headImg;
                if (self.headImg.length>0&&[UserDefaultsHelper readHeadimg].length == 0) {
                    [self updateHeadImageData];
                }
            }else {
                 [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [WSProgressHUD dismiss];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            XLog(@"error:%@",error);
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"当前手机号码已经绑定过账号了,请更换新的手机号"];
        }];
//        [CustomeManager POSTWithURLIndex:self.indexURL parameters:self.dict success:^(NSDictionary *dict) {
//        } failure:^(NSError *error) {
//        }];
    }
    
}
#pragma mark-上传头像
-(void)updateHeadImageData
{
    self.urlString = [NSString stringWithFormat:@"%@/user/changeHeadImg",kUrl];
    self.dict = @{
                  @"uid":[UserDefaultsHelper readUid],
                  @"headImg":self.headImg,
                  @"token":[UserDefaultsHelper readToken]
                  };
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        /**
         date =     {
         createtime = "<null>";
         headimg = "http://www.qichangkeji.vip/upload/img/b8318ddc-8032-4bcd-a2f8-9294e1892fcb.png";
         id = 12;
         nickname = "\U5566\U5566\U5566";
         password = "<null>";
         phone = 17621764088;
         type = 1;
         };
         message = "\U6210\U529f";
         status = 200;
         }
         */
        XLog(@"responseObject:%@",responseObject);
        NSString *message = [responseObject objectForKey:@"message"];
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
        [UserDefaultsHelper saveHeadimg:@"" value:self.headImg];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark-开启倒计时效果
-(void)openCountdown{
    
    int num = (arc4random() % 10000);
    self.randomNumber = [NSString stringWithFormat:@"%.4d", num];
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.getMsgBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                [self.getMsgBtn setTitleColor:kOrangeBg forState:UIControlStateNormal];
                self.getMsgBtn.userInteractionEnabled = YES;
                self.getMsgBtn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString *time = [NSString stringWithFormat:@"重新发送(%.2d)", seconds];
                [self.getMsgBtn setTitle:time forState:UIControlStateNormal];
                [self.getMsgBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                self.getMsgBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

@end
